<?php
class CMRPageResources extends CMRPage
{
	private function getDefaultContents()
	{
		$script = new EditDeleteFormScript();
		$html = $script->getHTML();
		
		$panel = new SearchPanel();
		$panel->setParentPage($this);
		$html .= $panel->getHTML();
		
		$html .= "<hr>\n";
		
		$datatable = new DataTable();
		$datatable->setParentPage($this);
		$datatable->setName("SearchResources");
		$datatable->setValue("SearchResources");
		$datatable->setViewable(true);
		$datatable->setEditable(false);
		$datatable->setDeletable(false);
		$datatable->setEditDeleteType("Hyperlink");

		$datatable->setDBTableName("Resources");
		$datatable->setDatabase($this->Database);
		$theRenderer = new DataTableRendererEdit($datatable);
		$theRenderer->setAction = "ListEvents";
		$datatable->setRenderer($theRenderer);
		$columns = array();
		$columns[] = new DataTableColumn("ResourceTitle","Title","");
		$columns[] = new DataTableColumn("ResourceDescription","Description","");
		$columns[] = new DataTableColumn("ResourceTypeID","Type","LongNameEnumeration");
		$columns[] = new DataTableColumn("LongName","Category","");
		//is an editor or supervisor
		$userGroup = $this->getUserGroup();
		if	(
			(!strcmp($userGroup,"Editors"))||
			(!strcmp($userGroup,"Supervisors"))
			)
		{
			$columns[] = new DataTableColumn("StatusID","Approved By","BodgeMultiEnumeration");
		}
		$datatable->setColumns($columns);
		$selectSQL = "SELECT res.ResourceID as ColumnID, ";
		$selectSQL .= "res.ResourceTitle, "; 
		$selectSQL .= "res.ResourceDescription, res.ResourceTypeID, "; 
		$selectSQL .= "stat.StatusID, cat.ResourceCategoryNameID, "; 
		$selectSQL .= "catnames.LongName ";
		$selectSQL .= "FROM Resources as res ";
//		$selectSQL .= "INNER JOIN ResourceStatuss as stat "; 
		$selectSQL .= "ON res.ResourceID = stat.ResourceID ";	
		$selectSQL .= "INNER JOIN ResourceCategorys as cat "; 
		$selectSQL .= "ON res.ResourceID = cat.ResourceID ";	
		$selectSQL .= "INNER JOIN ResourceCategoryNames as catnames "; 
		$selectSQL .= "ON cat.ResourceCategoryNameID = catnames.ResourceCategoryNameID ";	
		$datatable->setSelect($selectSQL);
		$datatable->setWhereMethod('SQL');
		
		$whereSQL = "(stat.StatusID = 1)";  // only live
		
		// Search Panel criteria
		$searchTypeSQL = "";
		if(isset($_POST['SearchTypes']))
		{
			foreach($_POST['SearchTypes'] as $TypeID)
			{
				$searchTypeSQL .= " res.ResourceTypeID = ".$TypeID." OR ";
			}
		}
		if($searchTypeSQL != "") $whereSQL .= " AND (".substr($searchTypeSQL,0,-3).") ";
		
		$searchCategorySQL = "";
		if(isset($_POST['SearchCategorys']))
		{
			foreach($_POST['SearchCategorys'] as $CatID)
			{
				$searchCategorySQL .= " cat.ResourceCategoryNameID = ".$CatID." OR ";
			}
		}
		if($searchCategorySQL != "") $whereSQL .= "AND (".substr($searchCategorySQL,0,-3).") ";
		
		$searchTextSQL = "";
		if(isset($_POST['SearchText']))
		{
			if($_POST['SearchText']!="")
			{
				$textTokens = explode(' ',$_POST['SearchText']);
				foreach($textTokens as $token)
				{
					$searchTextSQL .= " res.ResourceTitle LIKE '%".$token."%' OR ";
					$searchTextSQL .= " res.ResourceDescription LIKE '%".$token."%' OR ";
				}
			}
		}
		if($searchTextSQL != "") $whereSQL .= " AND (".substr($searchTextSQL,0,-3).") ";
				
		
		
		
		
		
		
		$datatable->setWhereSQL("WHERE (".$whereSQL.")");
		
		$datatable->setOrderBy("ResourceTitle");

		$html .= $datatable->getHTML();
		return $html;
	}

	private function getViewRecordContents()
	{
		$recordID = $_POST['RecordID'];
		$tableName = $_POST['DBTableName'];
		
		$script = new EditDeleteFormScript();
		$html = $script->getHTML();
		
		$panel = new PanelEditDBRecord($this->Database,$tableName,$recordID);
//		echo $tableName."<br>";
		
		// is there a type table??  (Field,table,ID
		$DBTable = new DBTable($this->Database,$tableName);
		$tableStructure = $DBTable->getTableStructure();
		$keys = array_keys($tableStructure);
		foreach($keys as $key)
		{
//			echo $key."<br>";
//			echo substr($key,-6)."<br>";
			if(substr($key,-6)=="TypeID")
			{
				// now find TypeID of typetable
				$sql = "SELECT ".$key." FROM ".$tableName." WHERE ".substr($tableName,0,-1)."ID = ".$recordID;
//				echo $sql."<br>";
				$this->Database->ExecuteSQL($sql);
				$row = $this->Database->getRow();
				$typeID = $row[$key];
//				echo $row[$key]."<br>";
				$sql = "SELECT LongName FROM ".substr($tableName,0,-1)."Types WHERE ".substr($tableName,0,-1)."TypeID = ".$typeID;
//				echo $sql."<br>";
				$this->Database->ExecuteSQL($sql);
				$row = $this->Database->getRow();
				$typeTable = str_replace(' ','',$row['LongName'])."s";
//				echo $typeTable."<br>";
				
				
				
				$panel->setTypeTable($key,$typeTable,$typeID);
//				echo $key."<br>";
				break;
			}
		}
		
		$panel->setYearRange(1400,2020);
		$panel->setReadOnly(true);
		$html .= $panel->getHTML();
		
		if($this->subAction=="Approve")
		{
			$input = new Hidden();
			$input->setName("SubAction");
			$input->setValue($this->subAction);
			$html .= $input->getHTML();
				
			$input = new Hidden();
			$input->setName("ResourceID");
			$input->setValue($recordID);
			$html .= $input->getHTML();
			
			// only allow approve if this record hasn't been approved by current user 
			
			$sql = "SELECT ActionDate,ActionTypeID FROM Actions WHERE UserID=".$this->UserID." AND ResourceID=".$recordID." ORDER BY ActionDate DESC";
			$this->Database->ExecuteSQL($sql);
//			echo $sql."<br>";
			$row = $this->Database->getRow();
			if ($row['ActionTypeID']=='2') // Approved by this user
			{
				$html .= "<p>You have already approved this resource</p>\n";
			}
			else
			{
				$approveButton = new Button();
				$approveButton->setName("Approve");
				$approveButton->setText("Approve");
				$approveButton->setOnClick("document.getElementById('Action').value = 'approve';document.getElementById('SubAction').value = 'UpdateActions';document.getElementById('PageForm').submit();");
				$html .= $approveButton->getHTML();
			}
		}
		
		return $html;
	}
	
	protected function getHTTPHeadersHTML()
	{
		if($this->Action=="ViewFile")
		{
			$recordID = $_POST['RecordID'];
			$tableName = $_POST['DBTableName'];
	
//			$sql = "SELECT BLOBFileName,BLOBFileSize,BLOBFileType FROM ".$tableName." WHERE ".substr($tableName,0,-1)."ID = ".$recordID;
			$sql = "SELECT FSFileName,FSFileSize,FSFileType FROM ".$tableName." WHERE ResourceIDP = ".$recordID;
			//			echo $sql."<br>";
			$this->Database->ExecuteSQL($sql);
			
			
			list($name, $type, $size) =  $this->Database->getRow(); 
//			echo $name." ".$type." ".$size." ".$recordID."<br>";
			$filename = "ResourceFiles/Files_FSFile_".$recordID;
			$content = file_get_contents($filename);

//			header("Content-length: $size");
			header("Content-type: $type");
			header("Content-Disposition: attachment; filename=\"$name\"");
			echo $content;
			
			$this->Database->close();
			exit;
		}
		
	}
	
	protected function getContents()
	{
		$html = "<td>";
		$html .= "<h1>Search for a Resource</h1>";
		switch ($this->Action)
		{
			case 'ViewRecord':
				$html .= $this->getViewRecordContents();
				break;
				
				default:
				$html .= $this->getDefaultContents();
				break;
		}
		
		
		$html .= "</td>";
		return $html;
		
	}
}